//
//  QBMainTabBar.swift
//  Wei91BoiOS
//
//  Created by bing on 16/3/19.
//  Copyright © 2016年 bing. All rights reserved.
//

import UIKit

// tabBarItem个数
let TabBarItemCount = 5

class QBMainTabBar: UITabBar {

    // 闭包属性
    var composeButtonCallback:(() -> ())?
    
    override func layoutSubviews() {
        
        super.layoutSubviews()
        
        // 计算item的宽度
        let width = frame.width / CGFloat(TabBarItemCount)
        
        // 计算最左边的这个frame，后面使用
        let originFrame = CGRect(x: 0, y: 0, width: width, height: frame.height)
        
        var index = 0
        
        for view in subviews {
            
            // 判断是否是UITabBarButton
//            let cls = NSClassFromString("UITabBarButton")
            
//            if view.isKindOfClass(NSClassFromString("UITabBarButton")!) {
            
                if view is UIControl && !(view is UIButton) {
                
                // 设置每个UITabBarButton的每个位置
//                view.frame = CGRect(x: CGFloat(index) * width, y: 0, width: width, height: frame.height)
                
                view.frame = CGRectOffset(originFrame, CGFloat(index) * width, 0)
                
                index += index == 1 ? 2 : 1
                
            }
        }
        // 设置加号按钮frame
        composeButton.frame = CGRect(x: 2 * width, y: 0, width: width, height: frame.height)
        
    }
    
    // MARK: - 按钮的点击事件
    func didClickComposeButton() {
        // 调用闭包
        composeButtonCallback?()
    }
    
    // MARK: - 懒加载
    /// 加好按钮
    private lazy var composeButton: UIButton = {
        
        let button = UIButton()
        
        // 设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        // 设置按钮图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        
        button.addTarget(self, action: "didClickComposeButton", forControlEvents: UIControlEvents.TouchUpInside)
        // 添加到tabBar上面
        self.addSubview(button)
        
        return button
    }()

}
